package com.zktravel.service.template;

import com.zktravel.constants.CommonConstant;
import com.zktravel.core.exception.ServiceException;
import com.zktravel.core.exception.VisibleException;
import com.zktravel.enums.CodeEnum;
import com.zktravel.mapper.TaProductTopMapper;
import com.zktravel.model.dto.template.TaProductTopDTO;
import com.zktravel.model.dto.template.Template;
import com.zktravel.model.po.TaProductTop;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TrProductTopServiceImpl implements TrProductTopService {
    @Resource
    private TemplateService shopService;

    @Resource
    private TaProductTopMapper taProductTopMapper;

    //置顶
    @Override
    public void goTop(TaProductTopDTO dto, Long shopId, Long userId) {
        // TODO TaProduct 获取商品信息
//        PlProduct plProduct = plProductMapper.selectById(dto.getProductId());
//        if (null == plProduct) {
//            throw new VisibleException(CodeEnum.PRODUCT_NOT_EXIST);
//        }
        // 获取模板的置顶数量
        Integer topNum = this.topNum(dto, shopId);
        // 根据type和shopId获取置顶数量
        Example example = new Example(TaProductTop.class);
        example.orderBy("sort").asc();
        example.createCriteria()
                .andEqualTo("shopId", shopId)
                .andEqualTo("isDeleted", CommonConstant.NO)
                .andEqualTo("categoryId", dto.getCategoryId());
        List<TaProductTop> topList = this.taProductTopMapper.selectByExample(example);

        Integer sort = CommonConstant.TOP_SORT;

        if (CollectionUtils.isNotEmpty(topList)) {
            List<TaProductTop> commonList;
            // 如果大于置顶数量
            if (topList.size() >= topNum) {
                throw new ServiceException(CodeEnum.PRODUCT_TOP_GT_MAX.getMessage());
            }
            // 如果置顶已有，则不再置顶
            commonList = topList.stream().filter(item -> item.getItemId().equals(dto.getItemId())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(commonList)) {
                return;
            }
        }
        TaProductTop top = new TaProductTop();
        top.setItemId(dto.getItemId());
        top.setShopId(shopId);
        top.setCategoryId(dto.getCategoryId());
        top.setSort(sort);
        top.setIsDeleted(CommonConstant.NO);
        top.setStatus(CommonConstant.AVAILABLE);
        top.setCreateUserId(userId);
        taProductTopMapper.insertSelective(top);

        // 此处修复置顶数据的顺序
        List<Long> idList = new ArrayList<>();
        for (TaProductTop item : topList) {
            idList.add(item.getItemId());
        }

        this.sort(shopId, dto.getCategoryId(), 2, idList);
    }

    //获取置顶数量
    @Override
    public Integer topNum(TaProductTopDTO dto, Long shopId) {
        List<Template> tplList = this.shopService.getShopTemplate(shopId);

        Integer num = 0;
        for (Template t : tplList) {
            Integer cat = dto.getCategoryId().intValue();
            if (t.getType().equals(cat)) {
                num = t.getNum();
            }
        }

        return num;
    }

    //取消置顶
    @Override
    public void cancelTop(TaProductTopDTO dto, Long shopId, Long userId) {
        TaProductTop top = new TaProductTop();
        top.setIsDeleted(CommonConstant.YES);
        top.setShopId(shopId);
        top.setCategoryId(dto.getCategoryId());
        top.setItemId(dto.getItemId());
        top.setUpdateUserId(userId);
        taProductTopMapper.cancelTop(top);
    }

    //取消置顶
    @Override
    public void cancelTopBySort(Long categoryId, Integer num, Long shopId, Long userId) {
        // 修改 大于num的置顶删除掉
        TaProductTop top = new TaProductTop();
        top.setIsDeleted(CommonConstant.YES);
        top.setShopId(shopId);
        top.setSort(num);
        top.setCategoryId(categoryId);
        top.setUpdateUserId(userId);
        this.taProductTopMapper.cancelTopBySort(top);
    }

    /**
     * @param shopId     店铺id
     * @param categoryId 置顶的类型
     * @param sortIndex  排序的初始值
     * @param ids        置顶数据的id
     */
    @Override
    public void sort(Long shopId, Long categoryId, Integer sortIndex, List<Long> ids) {
        // --------- 数据校验 ----------
        if (null == categoryId) {
            throw new VisibleException(CodeEnum.PRODUCT_TOP_TYPE_NOT_NULL);
        }
        if (null == ids) {
            throw new VisibleException(CodeEnum.PRODUCT_TOP_ID_SORT_NOT_NULL);
        }
        Integer thisSort = sortIndex;
        // --------- 修改条件整理 ----------
        List<TaProductTopDTO> list = new ArrayList<>();
        for (Long id : ids) {
            TaProductTopDTO updateParams = new TaProductTopDTO();
            updateParams.setShopId(shopId);
            updateParams.setCategoryId(categoryId);
            updateParams.setSort(thisSort);
            updateParams.setItemId(id);
            thisSort++;
            list.add(updateParams);
        }
        if (0 == list.size()) {
            return;
        }
        // --------- 数据落地 ----------
        taProductTopMapper.updateSort(list);
    }

    @Override
    public Integer getMaxTopNum(Long catId, Long shopId) {

        TaProductTop top = new TaProductTop();
        top.setShopId(shopId);
        top.setCategoryId(catId);

        return this.taProductTopMapper.getTopNum(top);
    }
}
